package network;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoClient {
    private Socket socket = null;
    public TcpEchoClient(String serverIP, int serverPort) throws IOException {
//
        socket = new Socket(serverIP,serverPort);
    }
    public void start() throws IOException {
        System.out.println("客户端启动！");
        Scanner scanner = new Scanner(System.in);
        try (InputStream inputStream = socket.getInputStream();
             OutputStream outputStream = socket.getOutputStream()){

            Scanner scannerNetwork = new Scanner(System.in);

            while (true){
//                1.从控制台读取数据
                System.out.println("请输入要发送的数据：");
//                String request = scanner.hasNext();
                String request = scanner.next();
//                2.把请求发送给服务器,发送的请求要有换行，和服务器中的scanner.next对应上
//                  因为上述通过next读到的request本身已经没有\n结尾，所以需要手动加上
                request += "\n";
                outputStream.write(request.getBytes());
//                3.从服务器读取到响应
                if (!scannerNetwork.hasNext()){
                    break;
                }
                String response = scannerNetwork.next();
//                4.把响应显示到控制台
                System.out.println(response);
            }
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient client = new TcpEchoClient("127.0.0.1",9090);
        client.start();
    }

}
